﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using MachiningHelper;
using MachiningHelper.ToolFile;
using System.Drawing;

namespace Skipper_Connector
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Reset();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                PassWord psw = new PassWord();
                psw.ShowDialog();
                if (psw.IsOk)
                {
                    serialPort1.Close();
                    serialPort2.Close();
                    if (string.IsNullOrEmpty(Config.InPort) || string.IsNullOrEmpty(Config.OutPort))
                        throw new Exception("请设置端口。");
                    serialPort1.PortName = Config.InPort;
                    serialPort2.PortName = Config.OutPort;
                    if (button1.Visible)
                    {
                        serialPort1.Open();
                        serialPort2.Open();
                    }
                }
            }
            catch (Exception ex)
            {
                button2.Visible = true;
                serialPort1.Close();
                serialPort2.Close();
                MessageBox.Show(ex.Message);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(Config.InPort) || string.IsNullOrEmpty(Config.OutPort))
                    throw new Exception("请设置端口。");
                serialPort1.Open();
                serialPort2.Open();
                button2.Visible = false;
                Config.PortState = true;
            }
            catch (Exception ex)
            {
                serialPort1.Close();
                serialPort2.Close();
                MessageBox.Show(ex.Message);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Close();
                serialPort2.Close();
                button2.Visible = true;
                Config.PortState = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                bool NormalMachine = Properties.Settings.Default.NormalMachine;
                string ts = serialPort1.ReadLine();
                string tss = GetMember(ts.Replace("\r", ""));//从扫码中截取需要的字符串；
                serialPort1.DiscardInBuffer();
                this.Invoke(new MethodInvoker(
                    delegate
                    {
                        richTextBox1.Text = string.Empty;
                        switch (ts)
                        {
                            case "ModeChange\r":
                                ModeChange();
                                break;
                            case "itest\r":
                                DoTest();
                                break;
                            case "ChangeToolFile\r":
                                ChangeToolFile();
                                break;
                            default:
                                OutputEngine(tss);
                                break;
                        }
                    }));
            }
            catch (Exception ex)
            {
                this.Invoke(new MethodInvoker(
                    delegate
                    {
                        textBox1.Clear();
                        textBox2.Clear();
                        NormalCode.Clear();
                        richTextBox1.Text = ex.Message;
                        this.Visible = true;
                        this.WindowState = FormWindowState.Normal;
                    }
                    ));
            }
        }

        private void button2_VisibleChanged(object sender, EventArgs e)
        {
            button1.Visible = !button2.Visible;
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked)
                Config.ModeState = 1;
            else
                Config.ModeState = 2;
            textBox1.Clear();
            textBox2.Clear();
            richTextBox1.Clear();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string extension = "*" + Config.FileExtension;
                DialogResult resault = MessageBox.Show("是否删除   " + Config.MachinePath + "   中的文件？", "Clear", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (resault == DialogResult.OK)
                {
                    foreach (string n in Directory.GetFiles(Config.MachinePath, extension))
                    {
                        File.Delete(n);
                    }
                }
                DialogResult resault2 = MessageBox.Show("是否删除   " + Config.CodePath + "   中的文件吗？", "Clear", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (resault2 == DialogResult.OK)
                {
                    foreach (string n in Directory.GetFiles(Config.CodePath, "*.csv"))
                    {
                        File.Delete(n);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                richTextBox1.Clear();
                if (!Config.IsMachiningTransform)
                    CopyCode(NormalCode.Text);

                else if (Config.NormalMachine)
                    DoNormal(NormalCode.Text);

                else if (radioButton1.Checked)
                {
                    if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
                        Skipper_Single_2(textBox2.Text);
                    else if (!string.IsNullOrEmpty(textBox1.Text))
                        Skipper_Single_1(textBox1.Text);
                }
                else
                    Skipper_Double(textBox2.Text);
            }
            catch (Exception ex)
            {
                textBox1.Clear();
                textBox2.Clear();
                NormalCode.Clear();
                richTextBox1.Text = ex.Message;
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == System.Windows.Forms.FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }//缩小到托盘

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            if (this.WindowState == System.Windows.Forms.FormWindowState.Minimized)
            {
                this.Visible = true;
                this.WindowState = System.Windows.Forms.FormWindowState.Normal;
                this.notifyIcon1.Visible = false;
            }
        }

        private void bttnMachingTransform_Click(object sender, EventArgs e)
        {
            btntrans(!Config.IsMachiningTransform);
            Config.IsMachiningTransform = !Config.IsMachiningTransform;
        }
        private void btntrans(bool istranfer)
        {
            if (istranfer)
            {
                bttnMachingTransform.Image = Image.FromFile(Application.StartupPath + @"\icon\transferON.png");
                bttnMachingTransform.Text = "      转换";
            }
            else
            {
                bttnMachingTransform.Image = Image.FromFile(Application.StartupPath + @"\icon\transferOFF.png");
                bttnMachingTransform.Text = "      锁定";
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //e.Cancel = true;
            //this.WindowState = FormWindowState.Minimized;
        }
        private string GetMember(string receive)
        {
            string flag = Config.FlagChar;
            string jobname = string.Empty;
            if (string.IsNullOrEmpty(flag) || receive.IndexOf(flag) < 0)
                return receive;

            var group = receive.Split(char.Parse(flag));
            jobname = Config.JobNameIndex < group.Count() ? group[Config.JobNameIndex] : string.Empty;

            receive = Config.CodeNameIndex < group.Count() ? group[Config.CodeNameIndex] : string.Empty;
            return receive;
        }

        private void DeletPreviousMachine()
        {
            string applePath = Path.Combine(Application.StartupPath, "MachieHistroy.apple");
            if (!File.Exists(applePath))
                return;

            StreamReader sr = new StreamReader(applePath);
            string path = sr.ReadLine();
            if (File.Exists(path))
                File.Delete(path);
        }

        private void ModeChange()
        {
            if (!Config.NormalMachine)
            {
                radioButton2.Checked = !radioButton2.Checked;
                radioButton1.Checked = !radioButton2.Checked;
            }
            else
            {
                AllPartMachine_radio.Checked = !AllPartMachine_radio.Checked;
                HdrillMachine_radio.Checked = !AllPartMachine_radio.Checked;
            }
            this.Visible = true;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
            this.notifyIcon1.Visible = false;
        }

        private void DoTest()
        {
            foreach (string n in Directory.GetFiles(Config.CodePath, "*.csv"))
            {
                Test GCodeTest = new MachiningHelper.Test();
                GCodeTest.makeGcode(n, Config.MachinePath, Config.CurrentToolFile);
                serialPort2.WriteLine(n + "\r");
            }
        }

        private void ChangeToolFile()
        {
            if (Config.CurrentToolFile == Config.Toolfile)
                Config.CurrentToolFile = Config.LastToolFile;
            else
                Config.CurrentToolFile = Config.Toolfile;

            FileInfo fi = new FileInfo(Config.CurrentToolFile);
            ToolNameLabel.Text = "当前类型：" + fi.Name.Replace(".tlfx", "");
        }

        private void OutputEngine(string inputStr)
        {
            if (!Config.IsMachiningTransform)//拷贝代码
                CopyCode(inputStr);
            else if (Config.NormalMachine)//通用模式
                DoNormal(inputStr);
            else
                DoSkipper100(inputStr);//Biesse Skipper100即时代码
        }
        private void CopyCode(string inputStr)
        {
            string fileExtension = Config.FileExtension;
            string bppFile = Path.Combine(Config.CodePath, inputStr + fileExtension);
            string progFile = Path.Combine(Config.MachinePath, inputStr + fileExtension);
            File.Copy(bppFile, progFile, true);
            NormalCode.Clear();
            if (!BusinessHelper.CheckRepeatBarcode(inputStr))
                return;
            serialPort2.WriteLine(inputStr + "\r");
        }
        private void DoNormal(string inputStr)
        {
            NormalCode.Text = inputStr;
            string csvfile = Path.Combine(Config.CodePath, inputStr + ".csv");

            MachiningPart part = new MachiningPart(csvfile);
            var parts = MachiningPart.GetParts(csvfile);
            if (AllPartMachine_radio.Checked)
                GCodeExporter.NormalMachining(Config.MachinePath, inputStr, Config.CurrentToolFile, parts, Config.TestMode);
            //GCodeExporter.NormalMachining(Config.MachinePath, inputStr, Config.CurrentToolFile, part, Config.TestMode);
            else
                GCodeExporter.HdrillMachining(Config.MachinePath, inputStr, Config.CurrentToolFile, part);

            NormalCode.Clear();

            if (!BusinessHelper.RecordPart(part, inputStr))
                return;

            serialPort2.WriteLine(inputStr + "\r");
        }
        private void DoSkipper100(string inputStr)
        {
            if (radioButton1.Checked)//单板模式
            {
                if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
                    Skipper_Single_1(inputStr);
                else if (!string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
                    Skipper_Single_2(inputStr);
            }
            else//双板模式
                Skipper_Double(inputStr);
        }
        private void Skipper_Single_1(string inputStr)
        {
            textBox1.Text = inputStr;
            string csvfile1 = Path.Combine(Config.CodePath, inputStr + ".csv");
            MachiningPart part = new MachiningPart(csvfile1);

            if (part.Border.Face5Only | part.Border.Face6Only)
            {
                string exportfileName = "N" + inputStr;
                textBox1.Clear();
                GCodeExporter.NormalPartMachining(Config.MachinePath, exportfileName, Config.CurrentToolFile, part);
                if (!BusinessHelper.RecordPart(part, inputStr))
                    return;
                serialPort2.WriteLine(exportfileName + "\r");
            }
            else
            {
                richTextBox1.Text = string.Format("{0} 为双面加工，请继续扫描另一面加工代码", part.Border.Description);
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
        }
        private void Skipper_Single_2(string inputStr)
        {
            string barcode1 = textBox1.Text;
            textBox2.Text = inputStr;
            string csvfile1 = Path.Combine(Config.CodePath, barcode1 + ".csv");
            string csvfile2 = Path.Combine(Config.CodePath, inputStr + ".csv");
            MachiningPart part1 = new MachiningPart(csvfile1);
            MachiningPart part2 = new MachiningPart(csvfile2);
            if (!ConditionChecker.IsOnePart(part1, part2))
                throw new Exception("当前扫描的机加工不是同片板件机加工。");
            string exportfileName = "D" + barcode1;
            textBox1.Clear();
            textBox2.Clear();
            GCodeExporter.FlipOnePartMachining(Config.MachinePath, exportfileName, Config.CurrentToolFile, part1, part2);

            if (!BusinessHelper.RecordPart(part1, barcode1) || !BusinessHelper.RecordPart(part2, inputStr))
                return;
            serialPort2.WriteLine(exportfileName + "\r");
        }
        private void Skipper_Double(string inputStr)
        {
            if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
                textBox1.Text = inputStr;
            else if (!string.IsNullOrEmpty(textBox1.Text))
            {
                textBox2.Text = inputStr;
                //保留或删除
                string csvfile = textBox1.Text;
                string insertfile = inputStr;
                string csvfileName = Path.Combine(Config.CodePath, csvfile + ".csv");
                string insertfileName = Path.Combine(Config.CodePath, insertfile + ".csv");

                string exportfileName = "P" + csvfile;
                MachiningPart part1 = new MachiningPart(csvfileName);
                MachiningPart part2 = new MachiningPart(insertfileName);
                textBox1.Clear();
                textBox2.Clear();

                if (ConditionChecker.IsDoubleFaceMachining(part1))
                    throw new Exception(part1.Border.Description + " 为双面加工，建议使用单板加工模式。");
                if (ConditionChecker.IsDoubleFaceMachining(part2))
                    throw new Exception(part2.Border.Description + " 为双面加工，建议使用单板加工模式。");
                if (!ConditionChecker.AllowFlipDoubleParts(part1, part2))
                    throw new Exception(string.Format("{0} 与 {1} 板件尺寸不一致。", part1.Border.Description, part2.Border.Description));

                switch (Config.PMOD)
                {
                    case "0":
                        GCodeExporter.doublePartFlipOne(Config.MachinePath, exportfileName, Config.CurrentToolFile, part1, part2);
                        if (!BusinessHelper.RecordPart(part1, csvfile) || !BusinessHelper.RecordPart(part2, inputStr))
                            return;
                        serialPort2.WriteLine(exportfileName + "\r");
                        break;

                    default://pmod=2
                        BiesseEditorUserData data = BiesseEditorUserData.LoadUserdata("2", Config.NPAN, "", "", "", "", "", "");
                        GCodeExporter.FlipDoublePartMachining(Config.MachinePath, exportfileName, "N" + insertfile, Config.CurrentToolFile, part1, part2, data);
                        if (!BusinessHelper.RecordPart(part1, csvfile) || !BusinessHelper.RecordPart(part2, inputStr))
                            return;
                        serialPort2.WriteLine(exportfileName + "\r");
                        break;
                        //if (GCodeExporter.doublePartFlipOne(Config.MachinePath, exportfileName, Config.CurrentToolFile, part1, part2))
                        //{
                        //    DialogResult result = MessageBox.Show(part1.Border.Description + "   加工存在用户定义的错误，是否仍要进行加工", "注意", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                        //    if (result == DialogResult.OK)
                        //        serialPort2.WriteLine(exportfileName + "\r");
                        //}
                        //else
                        //    serialPort2.WriteLine(exportfileName + "\r");
                }
            }
        }
        private void Reset()
        {
            System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName("缔盟加工中心对接程序");//获取指定的进程名   
            if (myProcesses.Length > 1)
            {
                MessageBox.Show("程序已启动！");
                Application.Exit();
            }

            try
            {
                BusinessHelper.Clear();
                if (!Config.NormalMachine)
                    panel1.Hide();
                Config.CurrentToolFile = Config.Toolfile;
                Config.IsMachiningTransform = true;
                FileInfo fi = new FileInfo(Config.CurrentToolFile);
                ToolNameLabel.Text = "当前类型：" + fi.Name.Replace(".tlfx", "");
                radioButton1.Checked = true;//默认模式为单板加工
                AllPartMachine_radio.Checked = true;//默认模式为全板加工
                btntrans(true);

                if (string.IsNullOrEmpty(Config.InPort) || string.IsNullOrEmpty(Config.OutPort))
                    throw new Exception("请设置端口。");
                serialPort1.PortName = Config.InPort;
                serialPort2.PortName = Config.OutPort;
                if (!Config.PortState)
                    button2.Visible = true;
                else
                {
                    button2.Visible = false;
                    serialPort1.Open();
                    serialPort2.Open();
                }
            }
            catch (Exception ex)
            {
                button2.Visible = true;
                serialPort1.Close();
                serialPort2.Close();
                MessageBox.Show(ex.Message);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //GCodeExporter.skipper100Test(Path.Combine(Config.CodePath, textBox1.Text + ".csv"), Path.Combine(Config.CodePath, textBox2.Text + ".csv"), Config.CurrentToolFile, Config.MachinePath);
            FinderWindows fw = new FinderWindows();
            fw.ShowDialog();
        }
    }
}
